<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="地址名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入地址名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

           
<!-- 列表   @row-click="rowClick" -->
    <el-table :data="deptList" 
            row-key="pid"  
            lazy 
             @row-click="rowClick"
            :load="load" 
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
      <el-table-column type="index" label="序号" align="center" width="220"/>
      <el-table-column  label="地址" prop="name" ></el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  type="text"  icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
          <el-button  type="text"   icon="el-icon-plus"   @click="handleAdd(scope.row)">新增</el-button>
          <el-button  v-if="scope.row.pid != 0"  type="text"  icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :closeOnClickModal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.pid !== 0">
            <el-form-item label="上级地址" prop="pid">
              <el-tree :data="deptOptions" :props="defaultProps" @node-click="nodeClick" :load="loadNode" lazy 
                    @check-change="handleCheckChange" show-checkbox></el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入地址名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

// import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      defaultProps: {//默认父节点-弹框
        children: 'children',
        label: 'name',
        isLeaf:true
      },

      // 部门树选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        id:'',
        info:'',
        name:'',
        pid:'',
      },
      // 表单校验
      rules: {
        // parentId: [
        //   { required: true, message: "上级地址不能为空", trigger: "blur" }
        // ],
        // name: [
        //   { required: true, message: "地址名称不能为空", trigger: "blur" }
        // ],
      },
      pid:0,
      name:'',
    };
  },
  created() {
    this.getList();
    // this.loadNode()
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.axios.post('/monitor/Sys/dept/getpid?pid=0').then(res => {
        this.deptList = res.data.data;
        console.log(res,'res-列表返回')
      });
    },
    load(tree, treeNode, resolve) {
      console.log(tree,treeNode,resolve);
      this.axios.post('/monitor/Sys/dept/getpid?pid='+this.pid).then(res=>{
          this.deptList =  res.data.data
      })
    },
    
    rowClick(data){//点击展开子集
      console.log(data,'点击表格data');
      this.pid = data.id
      this.dg()
      // this.load()
    },
// 弹框
     handleCheckChange(data, checked, indeterminate){//勾选事件
        console.log(data, checked, indeterminate,'333');
    },
    loadNode(node, resolve){
        if(node.level==0){
            return resolve(node.data)
        }
        setTimeout(()=>{
            resolve(node.data.children);
        },500)
    },
    nodeClick(data){//点击展开子集
      console.log(data,'点击表格data');
      this.pid = data.id
      this.dg()
    },
    dg(){
      if(this.pid!=0){
          this.axios.post('/monitor/Sys/dept/getpid?pid='+this.pid).then(res=>{
              if(res.status==200){
                  this.foreachFunc(this.deptList,res.data.data)
                  console.log('deptList-数组',this.deptList)

              }else{
                  alert(res.data.msg)
              }
          })
      }
    },
    foreachFunc(arr,children){
        var that=this
        arr.forEach(function(e,index){
            if(e.id==that.pid){
                e.children=children
            }else{
                that.foreachFunc(e.children,children)
            }
        })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        pid: undefined,
        name: undefined,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.pid = row.deptId;
      }
      this.open = true;
      this.title = "添加地址";
      
      this.axios.post('/monitor/Sys/dept/getpid?pid=0').then(res => {
        this.deptOptions = res.data.data;
        console.log(res,'res-列表返回')
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改地址";
      });
      let pid = row.id
      this.axios.post('/monitor/Sys/dept/getpid?pid='+pid).then(res => {
        this.deptOptions = res.data.data;
        console.log(res,'res-列表返回')
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
               let params ={
                name:this.form.name,
                pid:this.pid,
              }
              this.axios({url:'monitor/Sys/dept/update',method:'post',data:params,}).then(res => {
                this.$message({ type: "success", message: "修改成功!",});
                this.open = false;
                this.getList();
              });
          } else {
              let params ={
                name:this.form.name,
                pid:this.pid,//pid选中父级
              }
              this.axios({url:'monitor/Sys/dept/save',method:'post',data:params,}).then(res => {
              this.$message({ type: "success", message: "新增成功!",});
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDept(row.deptId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    }
  }
};
</script>